package com.hao.myfloatserver.server

import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PixelFormat
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.view.*
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.hao.myfloatserver.R
import com.hao.myfloatserver.utils.JumpUtils
import com.hao.myfloatserver.utils.RomUtil
import kotlin.math.abs


/**
 * Created by yy
 * @description: 悬浮窗服务
 */
class FloatingServer : Service() {

    private lateinit var wmParams: WindowManager.LayoutParams
    private lateinit var mWindowManager: WindowManager
    private lateinit var mWindowView: View
    private lateinit var mContainer: FrameLayout
    private var mParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
    private var mStartX: Int = 0
    private var mStartY: Int = 0
    private var mEndX: Int = 0
    private var mEndY: Int = 0
    var mFloatBinder: FloatBinder? = null

    private var hasAdded = false
    private var startTime = 0L

    private var currentIndex = -1;

    private var isShowMain = false

    var clazz: Class<*>? = null

    override fun onCreate() {
        super.onCreate()
        initWindowParams()
        initView()
        initClick()
    }

    /**
     * 初始化窗口配置
     */
    private fun initWindowParams() {
        mWindowManager = application.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        wmParams = WindowManager.LayoutParams()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
            req()
        } else if (RomUtil.isMiui()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                req()
            } else {
                wmParams.type = WindowManager.LayoutParams.TYPE_PHONE
            }
        } else {
            wmParams.type = WindowManager.LayoutParams.TYPE_TOAST
        }
        wmParams.format = PixelFormat.RGBA_8888
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
        wmParams.gravity = Gravity.START or Gravity.TOP
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT
    }

    private fun req() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            wmParams.type = WindowManager.LayoutParams.TYPE_PHONE
        }
    }

    private fun initView() {
        mWindowView = LayoutInflater.from(application).inflate(R.layout.float_window_layout, null)
        mContainer = mWindowView.findViewById<View>(R.id.llContainer) as FrameLayout
        mFloatBinder = FloatBinder()
    }

    /**
     * 添加view
     */
    private fun addWindowView2Window(view: View) {
        if (!hasAdded) {
            try {
                removeParentView(view)
                view.layoutParams = mParams
                mContainer.addView(view)
                mWindowManager.addView(mWindowView, wmParams)
                val mContainerWidth = mContainer.width
                var finalWidth = if (mContainerWidth == 0) 216 else mContainerWidth
                val width = mWindowManager.defaultDisplay.width
                val height = mWindowManager.defaultDisplay.height
                wmParams.x = (width - finalWidth)/2
                wmParams.y = height / 2
                hasAdded = true
                mWindowManager.updateViewLayout(mWindowView, wmParams)
            } catch (e: Exception) {
                try {
                    mWindowManager.removeView(mWindowView)
                } catch (e: Exception) {
                }
                hasAdded = false
            }


        }
    }

    /**
     * 移除view的父控件
     */
    private fun removeParentView(view: View) {
        val parent: ViewParent? = view.parent
        if (parent != null && parent is FrameLayout) {
            (parent as FrameLayout).removeView(view)
        }
    }


    /**
     * 移除控件
     */
    private fun removeWindowView() {
        if (hasAdded) {
            //移除悬浮窗口
            mWindowManager.removeView(mWindowView)
            hasAdded = false
        }
    }

    override fun onBind(intent: Intent): IBinder? {
        return mFloatBinder
    }


    @SuppressLint("ClickableViewAccessibility")
    private fun initClick() {
        val longPressDuration = 800L // 长按800ms
        var isLongPressed = false
        var longPressRunnable: Runnable? = null
        var isActionCancelled = false
        var moveThreshold = ViewConfiguration.get(applicationContext).scaledTouchSlop

        mWindowView.setOnTouchListener(View.OnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    startTime = System.currentTimeMillis()
                    mStartX = event.rawX.toInt()
                    mStartY = event.rawY.toInt()
                    isLongPressed = false
                    isActionCancelled = false

                    // 创建长按任务
                    longPressRunnable = Runnable {
                        if (!isLongPressed && !isActionCancelled) {
                            isLongPressed = true
                            handleLongClick()
                        }
                    }

                    // 启动长按检测
                    mWindowView.postDelayed(longPressRunnable, longPressDuration)

                    return@OnTouchListener false
                }
                MotionEvent.ACTION_MOVE -> {
                    mEndX = event.rawX.toInt()
                    mEndY = event.rawY.toInt()

                    // 只有当移动距离超过阈值才取消长按
                    if (abs(mStartX - mEndX) > moveThreshold || abs(mStartY - mEndY) > moveThreshold) {
                        // 取消长按检测
                        if (longPressRunnable != null) {
                            mWindowView.removeCallbacks(longPressRunnable)
                        }
                        isActionCancelled = true

                        // 处理拖动
                        wmParams.x = event.rawX.toInt() - mWindowView.measuredWidth / 2
                        wmParams.y = event.rawY.toInt() - mWindowView.measuredHeight / 2
                        mWindowManager.updateViewLayout(mWindowView, wmParams)
                        return@OnTouchListener true
                    }

                    return@OnTouchListener false
                }
                MotionEvent.ACTION_UP -> {
                    // 取消长按检测
                    if (longPressRunnable != null) {
                        mWindowView.removeCallbacks(longPressRunnable)
                    }

                    // 如果已经触发了长按，不再处理单击
                    if (isLongPressed) {
                        return@OnTouchListener false
                    }

                    // 如果移动距离过大，则取消点击处理
                    if (isActionCancelled) {
                        return@OnTouchListener true
                    }

                    // 处理为单击
                    handleSingleClick()
                    return@OnTouchListener false
                }
                MotionEvent.ACTION_CANCEL -> {
                    // 取消长按检测
                    if (longPressRunnable != null) {
                        mWindowView.removeCallbacks(longPressRunnable)
                    }
                    isLongPressed = true
                    isActionCancelled = true
                    return@OnTouchListener false
                }
            }
            return@OnTouchListener false
        })
    }





    // 处理单击事件
    private fun handleSingleClick() {
        // 在这里添加单击要执行的操作
        // 例如：显示/隐藏悬浮窗内容、改变悬浮窗样式等
        // 改变浮窗样式，生成一个图标，是背景蓝色，中间写着大写的数字1,点击一次换一个，到5的时候再点击变成1
        val mContainerWidth = mContainer.width
        var finalWidth = if (mContainerWidth == 0) 216 else mContainerWidth
        val width = mWindowManager.defaultDisplay.width
        val height = mWindowManager.defaultDisplay.height
        wmParams.x = (width - finalWidth)/2
        wmParams.y = height / 2
        mWindowManager.updateViewLayout(mWindowView, wmParams)
        mContainer.removeAllViews()
        if (this.currentIndex == -1 || this.currentIndex ==5){
            currentIndex = 0;
        }else{
            currentIndex = this.currentIndex + 1;
        }

        // 创建一个绿色圆圈配红色数字的图标
        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        // 创建圆形图标
        val circle = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888)
        val circleCanvas = Canvas(circle)

        // 先绘制绿色圆圈背景
        //颜色换成#2E8B57
        paint.color = Color.parseColor("#2E8B57")
        circleCanvas.drawCircle(100f, 100f, 100f, paint)

        // 再绘制红色数字
        paint.color = Color.parseColor("#FFFFFF")
        paint.textSize = 200f
        paint.textAlign = Paint.Align.CENTER
        //加粗
        paint.style = Paint.Style.FILL
        val fontMetrics = paint.fontMetrics
        val centerY = 100f - (fontMetrics.ascent + fontMetrics.descent) / 2
        circleCanvas.drawText(currentIndex.toString(), 100f, centerY, paint)

        mContainer.addView(ImageView(this).apply {
            setImageBitmap(circle)
            layoutParams = FrameLayout.LayoutParams(200, 200)
        })
        mWindowManager.updateViewLayout(mWindowView, wmParams)
    }


    // 处理长按事件（原双击逻辑）
    private fun handleLongClick() {
        Log.d("FloatingServer", "长按事件触发")
        try {
            // 添加调试信息
            Toast.makeText(this, "长按触发", Toast.LENGTH_SHORT).show()

            // 长按执行跳转操作
            if (this.isShowMain){
                //打开主程序窗口
                if (clazz != null) {
                    JumpUtils.jump(this, clazz)
                }
            }else{
                //回到桌面
                val homeIntent = Intent(Intent.ACTION_MAIN).apply {
                    addCategory(Intent.CATEGORY_HOME)
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK
                }
                startActivity(homeIntent)
            }
            this.isShowMain = !this.isShowMain;
        } catch (e: Exception) {
            e.printStackTrace()
            // 可以添加日志或者错误提示
            Toast.makeText(this, "无法跳转", Toast.LENGTH_SHORT).show()
        }
    }




    /**
     * 是否拦截
     * @return true:拦截;false:不拦截.
     */
    // 在 needIntercept() 方法中添加调试信息
    private fun needIntercept(): Boolean {
        val result = abs(mStartX - mEndX) > ViewConfiguration.getTouchSlop() ||
                abs(mStartY - mEndY) > ViewConfiguration.getTouchSlop()
        Log.d("FloatingServer", "needIntercept: $result, moveX: ${abs(mStartX - mEndX)}, moveY: ${abs(mStartY - mEndY)}")
        return result
    }


    inner class FloatBinder : Binder() {

        fun hide() {
            removeWindowView()
        }

        fun show(view: View) {
            addWindowView2Window(view)
        }

        fun setClazz(clazz: Class<*>?) {
            this@FloatingServer.clazz = clazz
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            mWindowManager.removeView(mWindowView)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}